from flask import Blueprint, request,Response
from pojo.result import Result  # 所有的依赖必须从根目录开始引入
from configuration.config import llmurl,llmport
import  requests
import json
import time
"""
模块1
"""
chat = Blueprint("chat", __name__, url_prefix="/chat")

#非流式响应
@chat.route("/unstreamresponse",methods = ['POST'])
def getUnstream():
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json',
    }
    json_list = []
    data = request.json
    # print("all if message")
    # print(data)
    data['stream'] = 'false'

    token = data.pop('token')

    resp = requests.post(llmurl +llmport +  '/chat/chat', headers=headers, json=data)
    print(resp.text)
    json_obj = json.loads(resp.text[5:])['text']
    json_list.append(json_obj)
    return vars(Result(200, "查询成功", json_list))  # 需要用vars包裹



#流式响应
@chat.route('/streamresponse',methods = ['POST'])
def check():
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json',
    }
    data = request.json

    token = data.pop("token")

    data['stream'] = 'true'
    content = ""
    def stream(content):
        #获取code
        resp = requests.post(llmurl+ llmport + '/chat/chat', json=data, stream=True, headers=headers)
        # 逐块读取响应体
        for chunk in resp.iter_content(chunk_size=1024, decode_unicode=True):
            content = chunk
            print(content)
            print(type(content))
            yield content
    return Response(stream(content), mimetype='text/plain')


